﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Timers;

namespace OfficeWorkstation
{
    class ClientListener
    {
        private int port = 7777;
        public static string data = null;
        public bool isStart = false;        
        private volatile bool _shouldStop = false;
        private ClientInfo _clientInfo;
        private Socket listener = null;
        private Socket handler = null;
        //Form1 thisForm = null;
        MainForm thisForm = null;

        //private Thread piThread = null;
        //private static System.Timers.Timer aTimer = null;

        MessageDispatcher _dispatch = null;

        public ClientListener(MainForm form1)
        {
            thisForm = form1;
            _clientInfo = new ClientInfo();
            _dispatch = new MessageDispatcher(_clientInfo);
        }        

        public void startListening(){
            byte[] bytes = new Byte[1024];

            System.Diagnostics.Debug.WriteLine(_shouldStop.ToString());
            /*
            aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(SendCheck);
            // Set the Interval to 5 seconds.
            aTimer.Interval = 5000;
             */ 
            // aTimer.Enabled = true;

            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress,port);
            
            //IPEndPoint localEndPoint = new IPEndPoint("127.0.0.1", 11000);

            //listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            try
            {
                isStart = true;
                listener.Bind(localEndPoint);
                
                listener.Listen(10);
                while (!_shouldStop)
                {
                    System.Diagnostics.Debug.WriteLine("Waiting for a connection...");                    
                    handler = listener.Accept();

                    data = "";
                    while (true)
                    {                        
                        bytes = new byte[1024];                        
                        int byteRec = handler.Receive(bytes);                        
                        data += Encoding.UTF8.GetString(bytes, 0, byteRec);
                        System.Diagnostics.Debug.WriteLine("_"+data+"_");
                        if (data.IndexOf("<EOF>") > -1)
                        {                            
                            break;
                        }
                    } 
                    
                    System.Diagnostics.Debug.WriteLine("Text receive: " + data.ToString());                   
                    thisForm.addMessage("Text receive: " + data.ToString(),false);
                    
                    String message = _dispatch.runImmediately(data.ToString(),handler,_clientInfo);
                    if (message != null)
                    {
                        String[] parts = message.Split(Constant.SEPERATOR_CHAR);
                        if (parts[0] == "0")
                            thisForm.addMessage("Receive welcome " + parts[1].ToString(), false);
                        if (parts[0] == Constant.REQUESTCONNECTING.ToString())                        
                            thisForm.addMessage("Your current code is: " + parts[1],false);
                        if (parts[0] == Constant.REQUESTPAIRCODE.ToString())
                        {
                            thisForm.addMessage("Your mobile phone has IP: " + parts[1], false);
                            //aTimer.Enabled = true;
                        }
                    }
                                                           
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch(Exception ex){
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
            System.Diagnostics.Debug.WriteLine("End server ");            
        }

        private void SendCheck(object source, System.Timers.ElapsedEventArgs e)
        {
            String str = ClientSender.SendMessage(_clientInfo.CodeValidation + "," + Constant.CHECKLIVING.ToString(), _clientInfo.Ip, 7787);
            //String[] temp = str.Split(',');
            thisForm.addMessage("Check ... here: " + str, false);            
            //aTimer.Enabled = false;                                   
        }

        public void stopListening()
        {
            if (isStart)
            {
                try
                {
                    System.Diagnostics.Debug.WriteLine("Stop the socket 1");
                    _shouldStop = true;
                    Thread.Sleep(1);
                    //handler.Shutdown(SocketShutdown.Receive);
                    //handler.Close();   

                    listener.Close();

                    isStart = false;
                    _shouldStop = false;
                    System.Diagnostics.Debug.WriteLine("Stop the socket 2");
                    _clientInfo.CodeValidation = "";
                    _clientInfo.Ip = "";                    
                    _clientInfo.Status = Constant.STATUS_NOT_CONNECTED;
                    

                }
                catch (SocketException ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString() + "");
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }
            }
        }


    }
}
